<?php

namespace app\api\service\admin;

use app\common\library\Auth;
use think\Validate;
use think\Db;

class StudentCourseCategoryService
{
    // 列表
    public static function index($data)
    {
        $limit = isset($data['limit']) ? $data['limit'] : 10;
        if (empty($data['course_id']) || !is_numeric($data['course_id'])) {
            return ['code'=>400, 'msg'=>'Invalid parameters', 'state'=>'INVALID_ARGUMENT', 'data'=>null];
        }
        // return $where;
        //分页查询
        $studio = \app\admin\model\StudentCourseCategory::where(['course_id'=>$data['course_id']])->field('course_id,category_id,category_name,abbreviation,color')->order('weigh', 'asc')
            ->paginate($limit)->each(function (&$item, $key){
                $item['sub_cat'] = \app\admin\model\SubCategory::where(['category_id'=>$item['category_id']])->field('subcat_id,subcat_name')->order('subcat_id', 'asc')->select();
            });
        return ['code'=>200, 'msg'=>'Successful', 'state'=>'OK', 'data'=>$studio];
    }

    // 保存
    public static function save($data)
    {
        // 基础验证规则
        $baseRules = [
            'course_id' => 'require',
            'category_name' => 'require',
            'abbreviation' => 'require',
            'color' => 'require',
        ];

        $baseMessages = [
            'course_id.require' => 'CourseId is not empty',
            'category_name.require' => 'Category Name is not empty',
            'abbreviation.require' => 'Abbreviation is not empty',
            'color.require' => 'Color is not empty',
        ];

        $validate = new Validate($baseRules, $baseMessages);
        if (!$validate->check($data)) {
            return ['code'=>400, 'msg'=>$validate->getError(), 'state'=>'INVALID_ARGUMENT', 'data'=>null];
        }

        // 启用事务将数据保存到数据库
        Db::startTrans();
        try {
            if(isset($data['category_id']) && $data['category_id']){
                // 更新操作额外验证
                $updateValidate = new Validate(['category_id' => 'require'], ['category_id.require' => 'CategoryId is not empty']);
                if (!$updateValidate->check($data)) {
                    Db::rollback();
                    return ['code'=>400, 'msg'=>$updateValidate->getError(), 'state'=>'INVALID_ARGUMENT', 'data'=>null];
                }

                $result = self::handleCategorySave($data, true);
            } else {
                // 新增操作
                $result = self::handleCategorySave($data, false);
            }

            Db::commit();
            return ['code'=>200, 'msg'=>'Successful', 'state'=>'OK', 'data'=>$result];
        } catch (\Exception $e) {
            Db::rollback();
            return ['code'=>400, 'msg'=>'Database error: '.$e->getMessage(), 'state'=>'DATABASE_ERROR', 'data'=>null];
        }
    }

    /**
     * 处理分类保存逻辑
     * @param array $data 输入数据
     * @param bool $isUpdate 是否为更新操作
     * @return array
     * @throws \Exception
     */
    private static function handleCategorySave($data, $isUpdate)
    {
        $subCatData = [];

        // 处理子分类数据
        if(isset($data['sub_cat']) && $data['sub_cat']){
            $data['sub_cat'] = str_replace('&quot;', '"', $data['sub_cat']);
            $sub_cat = json_decode($data['sub_cat'], true);

            if(json_last_error() !== JSON_ERROR_NONE) {
                throw new \Exception('Invalid sub category JSON data');
            }

            $data['has_subcategory'] = 1;
        } else {
            $data['has_subcategory'] = 0;
            $sub_cat = [];
        }
        unset($data['sub_cat']);

        // 保存主分类
        if($isUpdate) {
            $result = \app\admin\model\StudentCourseCategory::update($data);
        } else {
            $result = \app\admin\model\StudentCourseCategory::create($data);
        }

        // 处理子分类
        if(!empty($sub_cat)) {
            $subCatData = self::saveSubCategories($sub_cat, $result['category_id'], $isUpdate);
        }

        // 返回结果
        $result = $result->toArray();
        $result['sub_cat'] = $subCatData;

        return $result;
    }

    /**
     * 保存子分类数据
     * @param array $subCategories 子分类数据
     * @param int $categoryId 主分类ID
     * @param bool $isUpdate 是否为更新操作
     * @return array
     */
    private static function saveSubCategories($subCategories, $categoryId, $isUpdate)
    {
        $subCatData = [];
        $currentTime = time();

        foreach ($subCategories as $item) {
            if($isUpdate) {
                $updated = \app\admin\model\SubCategory::update($item);
                $subCatData[] = $updated->toArray();
            } else {
                $subCategoryData = [
                    'category_id' => $categoryId,
                    'subcat_name' => $item['subcat_name'],
                    'createtime' => $currentTime,
                    'updatetime' => $currentTime
                ];
                $created = \app\admin\model\SubCategory::create($subCategoryData);
                $subCatData[] = $created->toArray();
            }
        }

        return $subCatData;
    }


    // 详情
    public static function detail(array $data)
    {
        $auth = Auth::instance();
        $course_id = $data['course_id'] ?? null;
        $category_id = $data['category_id'] ?? null;

        if (!$course_id || !$category_id) {
            return ['code' => 400, 'msg' => 'Invalid parameters', 'state' => 'ERROR', 'data' => null];
        }

        // 主数据查询
        $course = model('admin/Course')
            ->where('course_id', $course_id)
            ->field('course_id,course_name,color')
            ->find();

        $category = model('admin/StudentCourseCategory')
            ->where('category_id', $category_id)
            ->field('category_id,category_name,abbreviation,color')
            ->order('category_id', 'asc')
            ->find();

        // 关联数据查询
        $subCategories = model('admin/SubCategory')
            ->where('category_id', $category_id)
            ->field('subcat_id,subcat_name')
            ->order('subcat_id', 'asc')
            ->select();

        $subjects = model('admin/StudentSubject')
            ->where('category_id', $category_id)
            ->field('subject_id,subject_name,abbreviation,color')
            ->order('subject_id', 'asc')
            ->select();

        $levels = model('admin/StudentCourseLevel')
            ->where('category_id', $category_id)
            ->field('subcat_id,level_id,level_name,abbreviation,age_range')
            ->order('level_id', 'asc')
            ->select();

        $semesters = model('admin/StudentSemester')
            ->where('category_id', $category_id)
            ->field('subcat_id,semester_id,semester_name')
            ->order('semester_id', 'asc')
            ->select();

        // 预加载lesson codes (TP5稳定写法)
        $semesterIds = array_column($semesters, 'semester_id');
        $lessonCodes = model('admin/StudentLessonCodes')
            ->where('category_id', $category_id)
            ->where('semester_id', 'in', $semesterIds)
            ->field('semester_id,lesson_id,code')
            ->order('lesson_id', 'asc')
            ->select();

        // 手动分组处理
        $groupedLessonCodes = [];
        foreach ($lessonCodes as $code) {
            $groupedLessonCodes[$code['semester_id']][] = $code;
        }

        // 组装数据
        foreach ($semesters as &$semester) {
            $semester['lesson_code'] = isset($groupedLessonCodes[$semester['semester_id']]) ? $groupedLessonCodes[$semester['semester_id']] : [];
        }

        $result = [
            'course' => $course,
            'category' => $category,
            'subject' => $subjects,
        ];

        // 处理子分类数据
        if (!empty($subCategories)) {
            $result['sub_category'] = [];
            foreach ($subCategories as $item) {
                // 按索引排列 level 数据
                $itemLevels = array_filter($levels, function($level) use ($item) {
                    return $level['subcat_id'] == $item['subcat_id'];
                });
                $item['level'] = array_values($itemLevels); // 重新索引数组

                // 按索引排列 semesters 数据
                $itemSemesters = array_filter($semesters, function($semester) use ($item) {
                    return $semester['subcat_id'] == $item['subcat_id'];
                });
                $item['semesters'] = array_values($itemSemesters); // 重新索引数组

                $result['sub_category'][] = $item;
            }
        } else {
            // 按索引排列 level 数据
            $result['level'] = array_values($levels); // 重新索引数组

            // 按索引排列 semesters 数据
            $result['semesters'] = array_values($semesters); // 重新索引数组
        }


        return ['code' => 200, 'msg' => 'Successful', 'state' => 'OK', 'data' => $result];
    }



    // 删除
    public static function del($data)
    {

        // 验证参数不能同时为空
        if (empty($data['category_id']) && empty($data['subcat_ids'])) {
            return ['code'=>400, 'msg'=>'category_id or subcat_ids must have one', 'state'=>'INVALID_ARGUMENT', 'data'=>null];
        }

        // 验证 category_id 必须是正整数
        if (!empty($data['category_id']) && (!is_numeric($data['category_id']) || $data['category_id'] <= 0)) {
            return ['code'=>400, 'msg'=>'category_id must be positive integer', 'state'=>'INVALID_ARGUMENT', 'data'=>null];
        }

        // 验证 subcat_ids 必须是数字或用逗号分隔的数字字符串
        if (!empty($data['subcat_ids']) && !preg_match('/^(\d+)(,\d+)*$/', $data['subcat_ids'])) {
            return ['code'=>400, 'msg'=>'subcat_ids must be numbers or comma-separated numbers', 'state'=>'INVALID_ARGUMENT', 'data'=>null];
        }

        try {
            Db::startTrans();

            // 删除分类逻辑
            if (!empty($data['category_id'])) {
                // 先检查并删除关联的子分类
                $hasSubCategories = \app\admin\model\SubCategory::where('category_id', $data['category_id'])->count();
                if ($hasSubCategories > 0) {
                    \app\admin\model\SubCategory::where('category_id', $data['category_id'])->delete();
                }

                // 删除主分类
                \app\admin\model\StudentCourseCategory::where('category_id', $data['category_id'])->delete();
            }

            // 删除子分类逻辑
            if (!empty($data['subcat_ids'])) {
                $subcatIds = explode(',', $data['subcat_ids']);
                \app\admin\model\SubCategory::whereIn('subcat_id', $subcatIds)->delete();
            }

            Db::commit();
            return ['code'=>200, 'msg'=>'Successful', 'state'=>'OK', 'data'=>null];
        } catch (\Exception $e) {
            Db::rollback();
            return ['code'=>400, 'msg'=>'Database error: '.$e->getMessage(), 'state'=>'DATABASE_ERROR', 'data'=>null];
        }
    }

    // 下拉查询
    public static function select()
    {
        $list = \app\admin\model\StudentCourseCategory::field('category_id,category_name,abbreviation')->order('weigh', 'asc')
            ->select();
        if($list){
            foreach ($list as $key=>$item) {
                $list[$key]['sub_cat'] = \app\admin\model\SubCategory::where(['category_id'=>$item['category_id']])->field('subcat_id,subcat_name')->order('subcat_id', 'asc')->select();
            }
        }
        return ['code'=>200, 'msg'=>'Successful', 'state'=>'OK', 'data'=>$list];
    }


}
